package pdf.demo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;
import utils.file.FileDownloadUtils;

public class PDFWaterMark {

    public static void main(String[] args) {
        String output = "/Users/lining/Desktop/pdftest/target1.pdf";
        String input = "/Users/lining/Desktop/pdftest/target.pdf";

        String remotePath = "http://paydayloanv4-1251122539.cos.ap-shanghai.myqcloud.com/20181117/SaveToCos/DSQ64756242181117131833.pdf";
        String filePath = "/Users/lining/Desktop/pdftest/hello";
        File temp = FileDownloadUtils.downloadRemoteFile2(remotePath,filePath);
        setWatermark(output,temp.getPath(),"李宁17609091223");
    }

    public static void setWatermark(String output, String input, String waterMark){
        BufferedOutputStream bos = null;
        PdfStamper stamper = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(new File(output)));
            PdfReader reader = new PdfReader(input);
            stamper = new PdfStamper(reader, bos);
            int total = reader.getNumberOfPages() + 1;
            PdfContentByte content;

            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.7f);
            int rotation = -35;
            int offsetX = 80;
            int offsetY = (int) (offsetX * Math.tan(Math.PI*-rotation/180)+0.5);
            for (int i = 1; i < total; i++) {
                content = stamper.getOverContent(i);// 在内容上方加水印
                content.beginText();
                content.setGState(gs);
                content.setColorFill(BaseColor.LIGHT_GRAY);
                content.setFontAndSize(base, 10);
                //content.setTextMatrix(70, 200);
                for(int y = 0; y < 850 ; y+= offsetY){
                    for(int x = 0;x<610;x+=offsetX){
                        content.showTextAligned(Element.ALIGN_CENTER, String.format("x=%s,y=%s",x,y), x, y, rotation);
                    }
                }
                content.endText();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                stamper.close();
            } catch (Exception e) {

            }
        }
    }
}
